package net.dgg.zz.credential.guidePriceConfigure.service;

import net.dgg.framework.tac.utils.idutil.DggKeyWorker;
import net.dgg.iboss.base.service.CmsService;
import net.dgg.iboss.base.util.DateUtil;
import net.dgg.tmd.foundation.platform.common.util.TranslateUtil;
import net.dgg.tmd.foundation.platform.session.SessionManager;
import net.dgg.tmd.foundation.platform.user.entity.UserEntity;
import net.dgg.zz.common.base.service.BaseService;
import net.dgg.zz.common.excption.CommonExcption;
import net.dgg.zz.common.service.CommonService;
import net.dgg.zz.common.systemRecord.entity.SystemRecord;
import net.dgg.zz.common.systemRecord.service.SystemRecordService;
import net.dgg.zz.common.utils.DateUtils;
import net.dgg.zz.common.utils.StringUtils;
import net.dgg.zz.common.utils.ValidateUtils;
import net.dgg.zz.credential.baseCredential.dao.BaseCredentialDao;
import net.dgg.zz.credential.excption.CertificateExcption;
import net.dgg.zz.credential.generalCredential.service.GeneralCredentialService;
import net.dgg.zz.credential.guidePriceConfigure.dao.GuidePriceConfigureDao;
import net.dgg.zz.credential.guidePriceConfigure.dto.GuidePriceDto;
import net.dgg.zz.credential.guidePriceConfigure.entity.GuidePriceConfigure;
import net.dgg.zz.credential.guidePriceConfigure.vo.GuidePriceVo;
import net.dgg.zz.credential.storageCapacity.dao.StorageCapacityDao;
import net.dgg.zz.credential.storageCapacity.entity.StorageCapacity;
import org.apache.commons.beanutils.ConvertUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zsx
 * @Title: GuidePriceConfigService
 * @ProjectName zzsc
 * @Description: 证书指导价配置
 * @date 2018/8/17 10:59
 */
@Service
public class GuidePriceConfigService extends BaseService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Resource
    private GuidePriceConfigureDao guidePriceConfigureDao;
    @Autowired
    private StorageCapacityDao capacityDao;
    @Autowired
    private SessionManager sessionManager;
    @Autowired
    private CmsService cmsService;
    @Autowired
    private TranslateUtil translateUtil;
    @Autowired
    private CommonService commonService;
    @Resource
    private GeneralCredentialService generalCredentialService;
    @Autowired
    private BaseCredentialDao baseCredentialDao;
    @Autowired
    private SystemRecordService systemRecordService;

    /*
     * @Author zsx
     * @Date 2018-08-17 05:08:01
     * @Description 分页查询指导价
     * @param params
     * @return List<Map>
     */
    public List<GuidePriceVo> queryGuidePriceWithPage(Map<String, Object> params) {
        if (params.containsKey("isAll") && params.get("isAll").equals("0")) {
            params.put("signOrgId", commonService.findUserSyb(sessionManager.getCurrentUser()));
        }
        if (null == params.get("orderColumn")) {
            params.put("orderDir", "desc");//排序方向
            params.put("orderColumn", "pc.create_time");//排序的列
        }
        List<GuidePriceVo> guidePrices = guidePriceConfigureDao.selectuidePriceByWithPage(params);
//        for (GuidePriceVo price:guidePrices){
//            String certificateArea =  commonService.translateCityCode(price.getCertificateArea());
//            price.setCertificateArea(certificateArea);
//        }
        String[] column = {"applicationScope", "certificateLevel"};
        return translateUtil.translateList(column, guidePrices);
    }

    /*
     * @Author zsx
     * @Date 2018-08-17 02:08:57
     * @Description 添加事业部
     * @param priceDto
     * @return Map<String,Object>
     */
    @Transactional
    public Map<String, Object> addGuidePrice(GuidePriceDto priceDto) {
        Map<String, Object> map = new HashMap<>();
        map.put("status", true);
        UserEntity user = this.sessionManager.getCurrentUser();
        if (null == user) {
            logger.info("未获取到当前登录人");
            map.put("status", false);
            map.put("msg", "未获取到当前登录人");
            return map;
        }
        //根据证书类型查询证书编码
        StorageCapacity storageCapacity = capacityDao.selectByAllType(priceDto);
        //不存在则添加
        if (null == storageCapacity) {
            storageCapacity = new StorageCapacity();
            storageCapacity.setId(DggKeyWorker.nextId());
            storageCapacity.setSignOrgId(priceDto.getSignOrgId());
            storageCapacity.setSignOrgName(priceDto.getSignOrgName());
            storageCapacity.setGeneralType(priceDto.getGeneralType());
            storageCapacity.setCertificateTypeId(priceDto.getCertificateTypeId());
            storageCapacity.setCertificateMajorId(priceDto.getCertificateMajorId());
            storageCapacity.setCertificateLevel(priceDto.getCertificateLevel());
            storageCapacity.setCertificateArea(priceDto.getCertificateArea());
            storageCapacity.setApplicationScope(priceDto.getApplicationScope());
            storageCapacity.setProvinceArea(priceDto.getProvinceArea());
            String code = cmsService.getBillNumber("CT");
            ValidateUtils.isTrue(StringUtils.isNotEmpty(code), CommonExcption.class, "单据号获取失败,请联系管理员");
            storageCapacity.setCertificateCode(code);
            this.saveOpt(storageCapacity, user);
            int count = capacityDao.insertSelective(storageCapacity);
        }
        //按照编码和日期查询当月是否存在配置
        String month = DateUtils.dateString(new Date(), DateUtils.yyyy_MM_dd_HH_mm_ss).substring(0, 7);
        GuidePriceConfigure configure = guidePriceConfigureDao.selectByCodeAndMonth(storageCapacity.getCertificateCode(), month, priceDto.getSignOrgId());
        if (null != configure) {
            map.put("status", false);
            map.put("msg", "本月已经存在配置，不能重复添加");
            return map;
        }
        configure = new GuidePriceConfigure();
        configure.setId(DggKeyWorker.nextId());
        configure.setCertificateCode(storageCapacity.getCertificateCode());
        configure.setSignOrgId(priceDto.getSignOrgId());
        configure.setSignOrgName(priceDto.getSignOrgName());
        configure.setCertificateGuidingPrice(priceDto.getCertificateGuidingPrice());
        configure.setHangUpGuidingPrice(BigDecimal.ZERO);
        configure.setMonth(month);
        this.saveOpt(configure, user);
        guidePriceConfigureDao.insertSelective(configure);

        //日志
        SystemRecord record = new SystemRecord();
        record.setSource("1");
        record.setOperateType("1");
        record.setWorkTableName("zz_guide_price_configure");
        record.setRemarks(priceDto.getSignOrgName() + "添加指导价");
        systemRecordService.save(record);
        return map;
    }

    /*
     * @Author zsx
     * @Date 2018-08-21 11:11:55
     * @Description
     * @param id 配置id
     * @param certificate_guiding_price 收证指导价
     * @param hang_up_guiding_price 使用指导价格
     * @return DggRestResponse
     */
    @Transactional
    public Map<String, Object> updateGuidePrice(Long id, BigDecimal certificateGuidingPrice, BigDecimal hangUpGuidingPrice, Integer type) {
        Map<String, Object> map = new HashMap<>();
        map.put("status", true);
        UserEntity user = this.sessionManager.getCurrentUser();
        if (null == user) {
            map.put("status", false);
            map.put("msg", "未获取到当前登录人");
            return map;
        }
        GuidePriceConfigure priceConfigure = guidePriceConfigureDao.selectByPrimaryKey(id);
        if (-1 == type) {
            priceConfigure.setCertificateGuidingPrice(certificateGuidingPrice);
            priceConfigure.setHangUpGuidingPrice(hangUpGuidingPrice);
        } else {
            priceConfigure.setStatus(type);
        }
        this.updateOpt(priceConfigure, user);
        guidePriceConfigureDao.updateByPrimaryKeySelective(priceConfigure);

        //日志
        SystemRecord record = new SystemRecord();
        record.setSource("1");
        record.setOperateType("2");
        record.setWorkId(id);
        record.setWorkTableName("zz_guide_price_configure");
        record.setRemarks("修改指导价");
        systemRecordService.save(record);
        return map;
    }

    /*
     * @Author zsx
     * @Date 2018-08-21 07:08:31
     * @Description 根据事业部id查询当前条数
     */
    public Integer selectGuidPriceCount(Long signOrgId) {
        String month = DateUtils.dateString(new Date(), DateUtils.yyyy_MM_dd_HH_mm_ss).substring(0, 7);
        return guidePriceConfigureDao.selectGuidPriceCount(signOrgId, month);
    }

    /*
     * @Author zsx
     * @Date 2018-08-21 06:08:38
     * @Description 复制指导价
     * @param signOrgId 事业部id
     * @param month 日期
     * @return Map(String,Object)
     */
    @Transactional
    public Map<String, Object> copyGuidePrice(Long signOrgId, String month) {
        Map<String, Object> map = new HashMap<>();
        map.put("status", true);
        UserEntity user = this.sessionManager.getCurrentUser();
        if (null == user) {
            map.put("status", false);
            map.put("msg", "未获取到当前登录人");
            return map;
        }
        //校验时间
        String copyd = month + "-01";
        Date copyDate = DateUtils.getDate(copyd, DateUtils.yyyy_MM_dd);
        String systemMonth = DateUtils.dateString(new Date(), DateUtils.yyyy_MM_dd_HH_mm_ss).substring(0, 7);
        Date systemDate = DateUtils.getDate(systemMonth + "-01", DateUtils.yyyy_MM_dd);
        if (copyDate.getTime() >= systemDate.getTime()) {
            map.put("status", false);
            map.put("msg", "只能复制本月以前的数据哦!");
            return map;
        }
        List<GuidePriceConfigure> priceConfigures = guidePriceConfigureDao.selectBySignOrgIdAndMonth(signOrgId, month);
        if (priceConfigures.size() == 0) {
            map.put("status", false);
            map.put("msg", "该事业部" + month + "无数据可复制哦");
            return map;
        }
        //删除本月已存在数据
        //TODO 后期可考虑只复制不存在的，已存在的不做删除
        guidePriceConfigureDao.deleteBySignOrgIdAndMonth(signOrgId, systemMonth);
        for (GuidePriceConfigure guidePrice : priceConfigures) {
            this.saveOpt(guidePrice, user);
//            guidePrice.setStatus(0);
            guidePrice.setMonth(systemMonth);
            guidePrice.setId(DggKeyWorker.nextId());
        }
        //批量插入数据
        guidePriceConfigureDao.insertGuidePriceConfig(priceConfigures);
        //日志
        SystemRecord record = new SystemRecord();
        record.setSource("1");
        record.setOperateType("41");
        record.setWorkTableName("zz_guide_price_configure");
        record.setRemarks(priceConfigures.get(0).getSignOrgName() + "复制了" + month + "的指导价");
        systemRecordService.save(record);
        return map;
    }


    /**
     * 计算指定证书专业的指导价
     *
     * @param params
     * @return
     */
    public Map countGuidePrice(Map params) {
        ValidateUtils.isTrue(params.containsKey("certificateSpecialty"), CertificateExcption.class, "证书专业不能为空");
        ValidateUtils.isTrue(params.containsKey("certificateTypeId"), CertificateExcption.class, "证书类型不能为空");
        ValidateUtils.isTrue(params.containsKey("certificateLevel"), CertificateExcption.class, "证书等级不能为空");
        ValidateUtils.isTrue(params.containsKey("certificateArea"), CertificateExcption.class, "证书地区不能为空");
        ValidateUtils.isTrue(params.containsKey("applicationScope"), CertificateExcption.class, "证书适用范围不能为空");
        ValidateUtils.isTrue(params.containsKey("signOrgId"), CertificateExcption.class, "证书所属事业部不能为空");
        params.put("month", DateUtil.dateToString(new Date(), "yyyy-MM"));
        params.put("status", "0");
        String certificateSpecialties = params.containsKey("certificateSpecialty") ? params.get("certificateSpecialty").toString() : null;
        Long[] certificateSpecialtys = (Long[]) ConvertUtils.convert(certificateSpecialties.split(","), Long.class);

        params.put("certificateSpecialtys", certificateSpecialtys);
        Map map = guidePriceConfigureDao.countGuidePrice(params);
        // 如果所有的证书专业都配置了指导价
        if (map.containsKey("countNum") && Integer.parseInt(map.get("countNum").toString()) == certificateSpecialtys.length) {
            return map;
        }
        return null;
    }

    /**
     * <p>@Description 使用或者编辑时计算指导价</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/8/30 0030 11:39 创建时间</p>
     * <p>@return</p>
     */
    public Map countGuidePriceBySubordinate(Map params) {
        ValidateUtils.isTrue(params.containsKey("certificateId"), CertificateExcption.class, "证书ID不能为空");
        Map codesMap = baseCredentialDao.queryCodesByCertificateId(params);
        //拿证书的专业去查指导价
        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("month", DateUtil.dateToString(new Date(), "yyyy-MM"));
        paramsMap.put("status", "0");
        String[] certificateCodes = codesMap.get("certificateCodes").toString().split(",");
        paramsMap.put("certificateCodes", certificateCodes);
        Map map = guidePriceConfigureDao.countGuidePrice(paramsMap);
        // 如果所有的证书专业都配置了指导价
        if (map.containsKey("countNum") && Integer.parseInt(map.get("countNum").toString()) == certificateCodes.length) {
            return map;
        }
        return null;
    }
}
